<template>
    <div id="health-record">
        <el-breadcrumb class="common-bread">
            <el-breadcrumb-item>健康数据分析</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="select-head">
            <el-date-picker v-model="date" type="date" placeholder="选择日期" :picker-options="myPickerOptions"></el-date-picker>
            <el-select v-if="user.userType < 2" v-model="schoolId" filterable clearable placeholder="请选择学校">
                <el-option v-for='item in schoolList' :label='item.schoolName' :value='item.schoolId' :key="item.schoolId">
                </el-option>
            </el-select>

            <el-select v-if="user.userType < 3" v-model="grade" placeholder="请选择年级">
                <el-option v-for='item in grades' v-if="schoolType.indexOf(item.type) > -1" :label='item.gradeName' :value='item.grade' :key="item.grade"></el-option>
            </el-select>
            <el-select v-model="classId" placeholder="请选择班级">
                <el-option v-for='item in classes' :label='item.className' :value='item.classId' :key="item.classId">
                </el-option>
            </el-select>
            <el-input type='text' placeholder="请输入学生姓名或者学籍号" v-model="keywords" @keyup.enter.native="searchHealthData"></el-input>
            <el-button type="primary" @click="searchHealthData()">搜索</el-button>
        </div>
        <div class="list contentBox">
            <el-row class="btn-box" type="flex" justify="space-around">
                <el-col :span="11" class="import-btn" @click.native="changeHealthData(1)">重点关注（{{importentData.length}}人）</el-col>
                <el-col :span="11" class="normal-btn" @click.native="changeHealthData(2)">查看其他学生（{{normalData.length}}人）</el-col>
            </el-row>
            <el-row>
                <el-col :span="6" v-for="item in dataList" :key="item.studentId">
                    <el-card :class="healthType == 1?'import-red mycard':'normal-blue mycard'" @click.native="skipHealthInfo(item)">
                        <div class="card-top">
                            <div class="test-score">
                                <div class="test-level" :title="item.name">{{item.name}}</div>
                                <div>{{item.className}}</div>
                            </div>
                            <div v-if="item.physicalScore" class="stu-info">
                                <div class="stu-classname">体测成绩</div>
                                <div class="stu-name">{{item.physicalScore}}</div>
                            </div>
                        </div>
                        <div :class="healthType == 1?'borcolor-red bottom':'color-blue bottom borcolor-blue'">
                            <span :class="item.sleepPass == 1 ? '' : 'red'">睡眠时间：{{item.sleepPass == 2 ? '-' :item.sleepData}}</span>
                            <div>
                                <span :class="item.heartRatePass == 1 ? '' : 'red'">平均心率：{{item.heartRatePass == 2 ?'-':item.heartRateData}}</span>
                                <span :class="item.stepPass == 1 ? '' : 'red'">运动步数：{{item.stepPass == 2 ? '-' :item.stepData}}</span>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
            <div v-if="hasHealthData" class="nodata">
                <img src="../../assets/noData.png">
                <p>暂无数据</p>
            </div>
        </div>
    </div>
</template>
<script>
    import { mapState, mapActions } from "vuex";
    export default {
        data() {
            return {
                dataList: [],
                normalData: [],
                importentData: [],
                healthType: 1,
                hasHealthData: true,
                date: new Date(new Date().getTime() - 24 * 3600000).format('yyyy/MM/dd'),
                keywords: '',
                schoolId: '',
                schoolType: '',
                schoolList: [],
                grade: '',
                grades: [
                    { grade: '1', gradeName: '一年级', type: 1 },
                    { grade: '2', gradeName: '二年级', type: 1 },
                    { grade: '3', gradeName: '三年级', type: 1 },
                    { grade: '4', gradeName: '四年级', type: 1 },
                    { grade: '5', gradeName: '五年级', type: 1 },
                    { grade: '6', gradeName: '六年级', type: 1 },
                    { grade: '7', gradeName: '初一', type: 2 },
                    { grade: '8', gradeName: '初二', type: 2 },
                    { grade: '9', gradeName: '初三', type: 2 },
                    { grade: '10', gradeName: '高一', type: 3 },
                    { grade: '11', gradeName: '高二', type: 3 },
                    { grade: '12', gradeName: '高三', type: 3 },
                ],
                classId: '',
                classes: [],
                healthInfo: {},
                searchNum: 1,
                myPickerOptions: {
                    disabledDate: (time) => {
                        return time.getTime() > Date.now() - 8.64e7
                    }
                },
            }
        },
        watch: {
            schoolId() {
                this.schoolType = this.schoolList.filter(item => {
                    return item.schoolId == this.schoolId
                })[0].schoolType;

                let mygrade = this.grades.filter(item => {
                    return this.schoolType.indexOf(item.type) > -1
                })
                if (this.grade == mygrade[0].grade) {
                    this.getClassList();
                }
                this.grade = mygrade[0].grade;
                this.classId = '';
            },
            grade() {
                this.classId = '';
                this.classes = [];
                this.getClassList()
            }
        },
        mounted() {
            if (this.user.userType == 2) {
                this.getUserSchool();
                if (this.grade > 0) {
                    this.getClassList()
                }
            } else if (this.user.userType == 3) {
                this.getTeacherClasses()
            } else {
                //获取学校列表
                this.getSchoolList();
            }

            if (this.$util.getStore("healthInfo") && this.$util.getStore("healthInfo") != '{}') {
                // 返回值
                this.healthInfo = JSON.parse(this.$util.getStore("healthInfo"));
                this.date = new Date(this.healthInfo.date * 1).format('yyyy/MM/dd');
                this.keywords = this.healthInfo.keywords;
                this.$util.removeStore('healthInfo');
            }
        },
        computed: mapState({ user: state => state.user }),
        methods: {
            searchHealthData() {
                this.getHealthList();
            },
            changeHealthData(type) {
                this.healthType = type;
                this.dataList = []
                if (type == 1) {
                    // 重点关注
                    this.dataList = this.importentData
                } else {
                    this.dataList = this.normalData
                }
                if (this.dataList && this.dataList.length > 0) {
                    this.hasHealthData = false
                } else {
                    this.hasHealthData = true
                }
            },
            getHealthList() {
                this.importentData = [];
                this.normalData = [];
                this.dataList = [];
                this.$axios.get('/jlp/admin/node/physique/list', {
                    params: {
                        classId: this.classId,
                        keywords: this.keywords,
                        date: new Date(this.date).getTime()
                    }
                }).then(response => {
                    if (response.data.error == 10000) {
                        let healthData = response.data.data.list
                        let classInfo = response.data.data.classInfo
                        let gradeName = '';
                        let className = '';
                        if (classInfo) {
                            gradeName = this.$util.gradeFormat(classInfo.grade * 1);
                            className = gradeName + classInfo.number + "班";
                        }
                        if (healthData && healthData.length > 0) {
                            // 数据处理
                            healthData.forEach(item => {
                                // let level = item.testInfo ? item.testInfo.level : ''
                                let time = new Date('2019/02/01 00:00').getTime();
                                let scoreLevel = '';
                                switch (item.testInfo.level * 1) {
                                    case 1:
                                        scoreLevel = '优秀';
                                        break;
                                    case 2:
                                        scoreLevel = '良好';
                                        break;
                                    case 3:
                                        scoreLevel = '及格';
                                        break;
                                    case 4:
                                        scoreLevel = '不及格';
                                        break;
                                    default:
                                        scoreLevel = '';
                                }
                                let student = {
                                    name: item.name,
                                    studentId: item.studentId,
                                    studentNumber: item.studentNumber,
                                    gender: item.gender,
                                    className: className,
                                    physicalScore: scoreLevel,
                                    physicalId: item.testInfo.physicalId || '',
                                    heartRateData: item.braceleInfo.heartRateData,
                                    heartRatePass: item.braceleInfo.heartRatePass,
                                    sleepData: new Date(time + item.braceleInfo.sleepData * 1000).format('hh小时mm分'),
                                    sleepPass: item.braceleInfo.sleepPass,
                                    stepData: item.braceleInfo.stepData,
                                    stepPass: item.braceleInfo.stepPass
                                };

                                if (student.heartRatePass == 1 && student.sleepPass == 1 && student.stepPass == 1) {
                                    // 正常数据
                                    this.normalData.push(student)
                                } else {
                                    // 重点关注
                                    this.importentData.push(student)
                                }
                                this.changeHealthData(1)
                            })
                        } else {
                            this.hasHealthData = true
                        }
                    } else {
                        this.hasHealthData = true
                    }
                }).catch(err => {
                    this.hasHealthData = true
                })
            },

            skipHealthInfo(row) {
                // 健康详情
                let params = {
                    studentId: row.studentId,
                    studentNumber: row.studentNumber,
                    physicalId: row.physicalId,
                    physicalScore: row.physicalScore,
                    date: new Date(this.date).getTime(),
                    keywords: this.keywords,
                    schoolId: this.schoolId,
                    schoolType: this.schoolType,
                    healthType: this.healthType,
                    grade: this.grade,
                    classId: this.classId,
                    gender: row.gender,
                    className: row.className,
                    name: row.name
                }
                this.$util.setStore("healthInfo", JSON.stringify(params));
                this.$util.refreshTo("/#/healthRecordInfo", {});
            },
            // 获取登录者学校信息
            getUserSchool() {
                this.schoolList = []
                this.$axios.get('/adminapi/v1/tools/schools/info', {
                    params: {
                        schoolId: this.user.schoolId
                    }
                }).then((res) => {
                    if (res.data.error == 10000) {
                        let pro = res.data.data;
                        let schoolType = '';
                        schoolType += pro.havePrimary ? 1 : '';
                        schoolType += pro.haveMiddle ? 2 : '';
                        schoolType += pro.haveHigh ? 3 : '';
                        this.schoolList.push({
                            schoolName: pro.name,
                            schoolId: pro.schoolId,
                            schoolType: schoolType
                        })
                        this.schoolId = pro.schoolId
                    }
                })
            },
            //获取学校列表
            getSchoolList() {
                this.schoolList = [];
                this.$util.getSchools().then(schools => {
                    schools.forEach(item => {
                        let schoolType = '';
                        schoolType += item.havePrimary ? 1 : '';
                        schoolType += item.haveMiddle ? 2 : '';
                        schoolType += item.haveHigh ? 3 : '';
                        this.schoolList.push({
                            schoolName: item.name,
                            schoolId: item.schoolId,
                            schoolType: schoolType
                        })
                    });
                    if (this.healthInfo.schoolId) {
                        this.schoolId = this.healthInfo.schoolId
                    } else {
                        this.schoolId = this.schoolList[0].schoolId || '';
                    }
                })
            },
            // 获取班级列表
            getClassList() {
                this.classes = [];
                this.searchNum += 1;
                this.$axios.get("/adminapi/v1/tools/classes/list", {
                    params: {
                        grade: this.grade,
                        schoolId: this.schoolId,
                        pageSize: 100,
                        pageNum: 1
                    }
                }).then(response => {
                    if (response.data.error == 10000) {
                        this.classes = [];
                        if (!response.data.data || !response.data.data.content) return;
                        let list = response.data.data.content;

                        list.forEach(item => {
                            let gradeName = this.$util.gradeFormat(item.grade * 1);
                            let className = gradeName + item.number + "班";
                            this.classes.push({
                                className: className,
                                classId: item.classId
                            })
                        })
                        this.classId = this.classes[0].classId;
                        console.log(this.searchNum)
                        if (this.searchNum < 3) {
                            this.getHealthList()
                        }
                    }
                })
            },
            getTeacherClasses() {
                this.classes = [];
                this.searchNum += 1;
                let phone = this.user.phone
                this.$axios.get("/adminapi/v1/tools/teachers/info/phone?phone=" + phone).then(response => {
                    if (response.data.error == 10000) {
                        let info = response.data.data;
                        this.classes = [];
                        if (info.teacherClassModelList && info.teacherClassModelList.length) {
                            info.teacherClassModelList.forEach(item => {
                                let gradeName = this.$util.gradeFormat(item.grade * 1);
                                let className = gradeName + item.number + "班";
                                // item.className = item.className ? className + `（${item.className}）` : className;
                                this.classes.push({
                                    classId: item.classId,
                                    className: className
                                });
                            });
                            this.classId = this.classes[0].classId;
                            if (this.searchNum < 3) {
                                this.getHealthList()
                            }
                        }
                    }
                })
            },

        }
    }
</script>
<style>
    #health-record .select-head {
        min-width: 1060px;
        background-color: #fff;
        padding: 20px 24px 10px;
        margin-left: 32px;
        margin-right: 32px;
    }

    #health-record {
        min-width: 1280px;
        min-height: 678px;
    }

    #health-record .btn-box {
        margin-bottom: 20px;
    }

    #health-record .import-btn {
        height: 50px;
        line-height: 50px;
        text-align: center;
        background-color: #FF7875;
        color: #fff;
        cursor: pointer;
    }

    #health-record .normal-btn {
        height: 50px;
        line-height: 50px;
        text-align: center;
        background-color: #91D5FF;
        color: #fff;
        cursor: pointer;
    }

    #health-record .mycard {
        padding: 0px;
        height: 180px;
        /* background-image: linear-gradient(-180deg, #3FD5FF 0%, #0398FF 100%); */
        margin-left: 20px;
        border-radius: 8px;
        cursor: pointer;
        position: relative;
        margin-bottom: 20px;
        overflow: visible;
    }

    #health-record .el-card__body {
        padding: 15px;
    }

    #health-record .color-blue {
        color: #44ABFF;
    }

    #health-record .borcolor-blue {
        border-bottom: #44ABFF 1px solid;
        border-left: #44ABFF 1px solid;
        border-right: #44ABFF 1px solid;
    }

    #health-record .borcolor-red {
        border-bottom: #F9A39E 1px solid;
        border-left: #F9A39E 1px solid;
        border-right: #F9A39E 1px solid;
    }

    #health-record .import-red {
        background-image: linear-gradient(-135deg, #FABB96 0%, #F9A39E 100%);
    }

    #health-record .normal-blue {
        background-image: linear-gradient(-90deg, #91D5FF 0%, #40A9FF 100%);
    }

    #health-record div.bottom {
        background: rgba(255, 255, 255, 0.9);
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 60px;
        padding: 0 15px;

        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
    }

    #health-record .red {
        color: #FC6A6F;
    }

    #health-record .card-top {
        padding-top: 10px;
        color: #fff;
    }

    #health-record .bottom>div>span:last-child {
        float: right;
    }

    #health-record .bottom>span {
        line-height: 32px;
    }

    #health-record .test-score {
        display: inline-block;
        text-align: center;
    }

    #health-record .stu-info {
        float: right;
        text-align: center;
    }

    #health-record .test-level {
        width: 140px;
        font-family: 'PingFangSC-Medium';
        font-size: 26px;
        line-height: 50px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    #health-record .stu-name {
        font-size: 24px;
        font-family: 'PingFangSC-Medium';

    }

    #health-record .stu-classname {
        line-height: 40px;
    }

    #health-record .nodata {
        padding-top: 80px;
        text-align: center;
        line-height: 36px;
    }
</style>